package com.serkol.ams.controller.api;


import cn.binarywang.wx.miniapp.api.WxMaService;
import com.serkol.ams.bean.Result;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.entity.Users;
import com.serkol.ams.entity.UsersAuthentication;
import com.serkol.ams.service.UsersAuthenticationService;
import com.serkol.ams.service.UsersService;
import com.serkol.annotation.IsLogin;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.exception.AuthException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/users/auth")
public class UsersAuthenticationApiController {


    @Autowired
    private UsersService userService;

    @Autowired
    private UsersAuthenticationService authenticationService;
    @Autowired
    private WxMaService wxMaService;

    @IsLogin
    @GetMapping("/info")
    @ResponseBody
    public Result info() throws AuthException {
        UsersAuthentication usersAuthentication = authenticationService.getInfo();
        if (usersAuthentication != null) {
            return Result.ok(usersAuthentication);
        } else {
          //  throw new AuthException(ResultCode.OK_CONTENT_NO);
            return Result.ok( );
        }
    }
    @IsLogin
    @PostMapping("/edit")
    @ResponseBody
    public Result edit(@RequestBody UsersAuthentication usersAuthentication) throws AuthException {
        System.out.println(usersAuthentication);
        LoginLog loginLog = AuthConstant.getLoginLog();
        usersAuthentication.setUserId(loginLog.getUserId());
        UsersAuthentication usersAuthentication1 = authenticationService.getInfo();
        boolean b = false;
        if (usersAuthentication1 != null) {
            usersAuthentication.setId(usersAuthentication1.getId());
            b = authenticationService.updateById(usersAuthentication);


        } else {
            b = authenticationService.save(usersAuthentication);
        }

        if (b) {
             Users byUserId = userService.findByUserId(usersAuthentication.getUserId());
             if (byUserId != null) {
                 if (StringUtils.isEmpty(byUserId.getPhone())) {
                     byUserId.setPhone(usersAuthentication.getPhone());
                     userService.updateById(byUserId);
                 }
             }

            return Result.ok(usersAuthentication);
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_PRECONDITION_FAILED);
        }
    }


}
